package com.navinfo.platform.score.service.impl;

import com.navinfo.platform.score.service.ConfigLoadService;
import org.apache.commons.cli.CommandLine;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;

import java.io.*;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.Properties;

/**
 * @author 沈东生
 */
public class ConfigLoadServiceYaml extends ConfigLoadService implements Serializable{
    static final Logger LOGGER = LoggerFactory.getLogger(ConfigLoadServiceYaml.class);

    @Override
    public Properties load() {
        InputStream in = this.inputStream;
        Properties props = new Properties();
        try {

            Yaml yaml = new Yaml(new SafeConstructor());

            Map<Object, Object> ret = (Map<Object, Object>) yaml.load(new InputStreamReader(in));
            if (null != ret) {
                for (Map.Entry<Object, Object> en : ret.entrySet()) {
                    props.setProperty(en.getKey().toString(), en.getValue().toString());
                }
            }
        } catch (Exception ex) {
            LOGGER.error(ex.getMessage(), ex);
        } finally {
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                    LOGGER.error(e.getMessage(), e);
                }
            }
        }
        return props;
    }
    public Properties loadProps(String fileName) throws URISyntaxException, FileNotFoundException {
        File directory = new File(ConfigLoadServiceYaml.class.getProtectionDomain()
                .getCodeSource()
                .getLocation()
                .toURI()
                .getPath()).getParentFile();
        InputStream in = new FileInputStream(directory.getAbsolutePath() + "/" + fileName);
        this.setInputStream(in);
        Properties config = this.load();
//        Properties cmdProps = cmd.getOptionProperties("D");
//        if (cmdProps != null) {
//            cmdProps.forEach((k, v) -> {
//                config.put(k, v);
//            });
//        }
        return config;
    }
}
